package com.smstransmit.reciver

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.telephony.SmsMessage
import android.text.TextUtils
import android.util.Log
import com.smstransmit.control.SmsControl
import java.text.SimpleDateFormat
import java.util.*

/**
 * Created by shijie.guo on 2017/9/11.
 */
class SmsReciver : BroadcastReceiver() {
    override fun onReceive(context: Context, intent: Intent?) {
        Log.d("sms", intent?.action)
        val pdus = intent?.getExtras()?.get("pdus") as Array<Any>
        var contents = StringBuffer()
        var sender = ""
        val time = ""
        for (pdu in pdus) {
            val smsMessage = SmsMessage.createFromPdu(pdu as ByteArray)
            if (TextUtils.isEmpty(sender))
                sender = smsMessage.getDisplayOriginatingAddress()
            val content = smsMessage.getMessageBody()
            contents.append(content)
            if (TextUtils.isEmpty(time)) {
                val date = smsMessage.getTimestampMillis()
                val timeDate = Date(date)
                val simpleDateFormat = SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
                val time = simpleDateFormat.format(timeDate)
            }
        }
        println("内容:" + contents.toString())
        println("来自:" + sender)
        println("时间:" + time)

        SmsControl.send(context, " 内容：${contents};来自${sender};时间：${time} ")
    }
}